package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.RedisConstants;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.entity.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        if (!RegexUtils.isInvalidPhone(phone)) {
            return Result.fail("手机号码格式错误");
        }
        String code = RandomUtil.randomNumbers(6);
        //保持手机号码和验证码到session    ——》 优化为redis
//        session.setAttribute("code_phone",phone);
//        session.setAttribute("code",code);
        redisTemplate.opsForValue().set(FIRST_LOGIN+phone, phone, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(LOGIN_PHONE_CODE+phone, code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.debug("验证码发送成功，为："+code);
        log.debug("验证码有效期："+LOGIN_CODE_TTL+"分钟");
        return Result.ok("验证码发送成功");
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //判断是否合规
        String phone = loginForm.getPhone();
        if (!RegexUtils.isInvalidPhone(phone)) {
            return Result.fail("手机号码格式错误");
        }
        //String  code_phone = (String) session.getAttribute("code_phone");
        String code_phone = redisTemplate.opsForValue().get(RedisConstants.FIRST_LOGIN + phone);
        //如果不为空说明是刚注册
        if (code_phone != null && !phone.equals(code_phone)) {
            return Result.fail("接收验证码的手机号码和登录号码不是同一个！");
        }
        String loginCode = redisTemplate.opsForValue().get(LOGIN_PHONE_CODE + phone);
        if (!loginForm.getCode().equals(loginCode)) {
            return Result.fail("验证码错误！");
        }
        //根据手机号码查询用户
        User user = query().eq("phone", phone).one();
        //不存在user则创建新的用户
        if (user == null) {
            user = registryUser(phone);
        }
        //存入session
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        userDTO.setUserId(1000L);
        String token = createToken(userDTO);
        //session.setAttribute("user",userDTO);
        Map<String,String> beanMap = new HashMap<>();
        beanMap.put("userId",userDTO.getUserId().toString());
        beanMap.put("nickName",userDTO.getNickName());
        beanMap.put("icon",userDTO.getIcon());
        redisTemplate.opsForHash().putAll(LOGIN_USER+token,beanMap);
        //30分钟有效期
        redisTemplate.expire(LOGIN_USER+token,30L,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    /**
     * 生成token
     * @param userDTO
     * @return
     */
    private String createToken(UserDTO userDTO) {
        Map<String,Object> payload = new HashMap<String,Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, DateTime.now());
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, DateTime.now().offset(DateField.MINUTE,30));
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, DateTime.now());
        //载荷
        payload.put("userName", userDTO.getNickName());
        payload.put("userId", userDTO.getUserId());

        String key = userDTO.getNickName();
        String token = JWTUtil.createToken(payload, key.getBytes());
        return token;
    }

    private User registryUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setCreateTime(LocalDateTime.now());
        user.setNickName("user_"+phone);
        save(user);
        return user;
    }
}
